<script setup lang="ts">
	import {
		onLaunch,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import {
		useSystemStore
	} from './stores/system'
	import {
		useUserStore
	} from './stores/user'
	import { LoginParam } from './types/api'

	// #ifdef MP-WEIXIN
	import {
		useNovelStore
	} from './stores/novel'
	import {
		getBookshelfStatus,
		setBookshelfStatus,
		getContents,
		payBookChapter,
		getRechargeList
	} from './api/index'
	import { SDK } from '@dn-sdk/miniprogram/build/index.js'
	const novelPlugin = requirePlugin('novel-plugin')
	novelPlugin.setLoggerConfig({
		//info: true,
		//debug: true,
		//log: true,
		//warn: true,
		error: true,
	})


	// #endif



	const userStore = useUserStore()

	onLaunch((params : App.LaunchShowOption) => {
		const systemStore = useSystemStore()
		systemStore.getSystemInfo()
		uni.getProvider({
			service: 'oauth',
			success: (res) => {
				const providers = res.provider || []
				userStore.provider = providers[0]
			}
		})
		login(params)

		console.log('App Launch')

		// #ifdef MP-WEIXIN
		// 订阅小程序初始化成功的事件
		novelPlugin.onPageLoad(onNovelPluginLoad)

		// #endif
	})

	const login = (params : any) => {
		const query : LoginParam = params.query || {}
		if (JSON.stringify(query) != "{}") {
			userStore.loginParam = query
		}
		userStore.Login()

		if (params.path == 'pages/mpurl/mpurl') {

			return
		}

	}

	// #ifdef MP-WEIXIN

	async function onNovelPluginLoad(data : any) {
		const appidinfo = uni.getAccountInfoSync();
		const isDebug = true; // 调试模式
		SDK.setDebug(isDebug);
			 
		const sdk = new SDK({
		    user_action_set_id: 1213469375,
		    secret_key: 'b75be5fef8ba3101ef455a818e4bfe64',
		    appid: appidinfo.miniProgram.appId
		});
			 
		// 挂载到全局
		getApp().sdk = sdk;
		console.log('初始化成功')
		const novel = useNovelStore()
		novel.novelManagerId = data.id

		// data.id 句柄 用来获取novelManager实例
		const novelManager = novelPlugin.getNovelManager(data.id)
		// 返回插件页对应的launchOptions
		const launchOptions = novelManager.launchOptions
		if (launchOptions.path == '__plugin__/wx293c4b6097a8a4d0/pages/novel/index') {
			login(launchOptions)
		}

		// getBookId() 返回当前manager对应的bookId
		const bookId = novelManager.getBookId()
		novel.book_id = bookId
		try {
			const {
				bookshelfStatus
			} = await getBookshelfStatus({
				book_id: bookId
			}) || {}
			// params.bookshelfStatus number类型 0 代表用户取消添加书架 1 代表用户添加书架
			// 默认情况该值为0 即未添加
			novelManager.setBookshelfStatus({
				bookshelfStatus: bookshelfStatus || 0
			})
		} catch (e) {
			//TODO handle the exception
		}
		// 关闭分享
		novelManager.setShareParams({
			enable: false,
		})
		//读后推荐
		novelManager.setRecommendInfo({
			homeButton: {
				url: '/pages/index/index',
				mode: 'navigateTo',
			},
		})


		// 监听用户点击书架的事件
		// params.bookshelfStatus number类型 0 代表用户取消添加书架 1 代表用户添加书架
		novelManager.onClickBookshelf(async (params : any) => {
			try {
				const {
					bookshelfStatus
				} = await setBookshelfStatus({
					book_id: bookId,
					bookshelfStatus: params.bookshelfStatus === 0 ? 1 : 0
				})
				novelManager.setBookshelfStatus({
					bookshelfStatus
				})
			} catch (e) {
				//TODO handle the exception
			}
		})

		// setContents 设置目录信息(Object params)
		// params.contents Array类型 是一个代表各个章节信息的数组
		// params.contents[i].index  number类型 代表章节下标(章节下标从0开始)
		// params.contents[i].status number类型 代表章节状态(1 免费章节 2 未付费章节 3 已付费章节 其余值非法)
		let numRes = [];
		try {
			const res = await getContents({
				book_id: bookId
			})
			numRes = res;
			console.log('书籍信息', res);
			novelManager.setContents({
				contents: res || []
			})
		} catch (e) {
			//TODO handle the exception
		}



		novelManager.onUserTriggerEvent(async (params : any) => {
			novel.chapterIndex = params.chapter_index
			novel.book_id = params.book_id
			const userinfo = userStore.loginInfo

			const systemInfo = uni.getSystemInfoSync()
			if ((userinfo['link_id'] == 0) && systemInfo.osName === 'ios') {
				console.log('用户信息', userinfo)

				novelManager.setChargeWay({
					globalConfig: {
						mode: 1,
						tip: '由于相关规范，iOS功能暂不可用',
					},
				})

			} else {
				novelManager.setChargeWay({
					globalConfig: {
						mode: 1,
						buttonText: '解锁',
						showButton: true
					},
				})
				if (params.event_id == 'change_chapter') {
					// console.log('切换章节', params.event_id)
					// console.log('第几章', novel.chapterIndex)
					// console.log('章节状态', numRes[novel.chapterIndex].status)
					if (numRes[novel.chapterIndex].status == 2) {

						console.log('开始书币解锁')
						const novelManager = novelPlugin.getNovelManager(novel.novelManagerId)
						//novelManager.paymentCompleted()
						const res = await payBookChapter({
							book_id: novel.book_id,
							ChapterIndex: novel.chapterIndex
						})

						if (res == 1) {
							console.log('书币解锁成功', res)
							novelManager.paymentCompleted()

						} else {

							const userStore = useUserStore()
							console.log('解锁失败', userStore)
						}
					} else {
						novelManager.paymentCompleted()
					}
				}

			}

		})



	}
	// #endif

	onShow(() => {
		console.log('App Show')
	})

	onHide(() => {
		console.log('App Hide')
	})
</script>

<style lang="scss">
	/*每个页面公共css */
	.container {
		position: relative;
		min-height: 100vh;
		font-family: PingFangSC-Regular, PingFang SC;
		font-weight: 400;
		background: #F5F5F5;
		@include flex($direction: column);
		box-sizing: border-box;
	}
</style>